/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.manager.search;

import br.com.foxline.enums.PropertySystem;
import br.com.foxline.enums.TypeDocument;
import br.com.foxline.model.CharterSDI;
import br.com.foxline.model.Part;
import br.com.foxline.model.Stamp;
import br.com.foxline.model.People;
import br.com.foxline.model.TypeStamp;
import br.com.foxline.model.City;
import br.com.foxline.model.Quality;
import br.com.foxline.model.Annex;
import br.com.foxline.service.*;
import br.com.foxline.util.ConverterImg;
import br.com.foxline.util.Msg;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author roniere
 */
@ManagedBean
@ViewScoped
public class ManagerSearchCesdi implements Serializable {

    @EJB
    StampService stampService;
    @EJB
    TypeStampService typeStampService;
    @EJB
    CharterSDIService charterService;
    @EJB
    PeopleService peopleService;
    @EJB
    QualityService qualityService;
    @EJB
    AnnexService annexService;
    private CharterSDI charter;
    private CharterSDI charterShow;
    private CharterSDI charterEdit;
    private List<CharterSDI> charterSDIs;
    private People people;
    private People peopleEdit;
    private Part part;
    private Part partEdit;
    private List<Part> parts;
    private Stamp stamp;
    private Stamp stampEdit;
    private List<Stamp> stamps;
    private TypeStamp typeStampObj;
    private TypeStamp typeStampObjEdit;
    private Annex annex;
    private List<Annex> annexs;
    private City cityResidencia;
    private Annex annexToRemove;

    @PostConstruct
    public void init() {
        charter = new CharterSDI();
        charterEdit = new CharterSDI();

        people = new People();
        people.setTipoDocumento(TypeDocument.CPF);
        peopleEdit = new People();
        peopleEdit.setTipoDocumento(TypeDocument.CPF);

        part = new Part();
        partEdit = new Part();

        parts = new ArrayList<Part>();

        stamp = new Stamp();
        stampEdit = new Stamp();

        stamps = new ArrayList<Stamp>();
        typeStampObj = new TypeStamp();
        typeStampObjEdit = new TypeStamp();
        annexs = new ArrayList<Annex>();
        cityResidencia = new City();

        paramGet();
    }

    public void paramGet() {
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        String cesdiShow = params.get("cesdiShow");
        String cesdiEdit = params.get("cesdiEdit");

        try {
            if (cesdiShow != null) {
                charterShow = charterService.find(Long.parseLong(cesdiShow));
                if (charterShow != null) {
                    charterShow.setAnnex(annexService.getAnnexByCharter(charterShow));
                }
            } else if (cesdiEdit != null) {
                System.err.println(cesdiEdit);
                charterEdit = charterService.find(Long.parseLong(cesdiEdit));
                if (charterEdit != null) {
                    charterEdit.setAnnex(annexService.getAnnexByCharter(charterEdit));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public TypeStamp getTypeStampObjEdit() {
        return typeStampObjEdit;
    }

    public void setTypeStampObjEdit(TypeStamp typeStampObjEdit) {
        this.typeStampObjEdit = typeStampObjEdit;
    }

    public CharterSDI getCharterEdit() {
        return charterEdit;
    }

    public void setCharterEdit(CharterSDI charterEdit) {
        this.charterEdit = charterEdit;
    }

    public Part getPartEdit() {
        return partEdit;
    }

    public void setPartEdit(Part partEdit) {
        this.partEdit = partEdit;
    }

    public People getPeopleEdit() {
        return peopleEdit;
    }

    public void setPeopleEdit(People peopleEdit) {
        this.peopleEdit = peopleEdit;
    }

    public Stamp getStampEdit() {
        return stampEdit;
    }

    public void setStampEdit(Stamp stampEdit) {
        this.stampEdit = stampEdit;
    }

    public Annex getAnnex() {
        return annex;
    }

    public void setAnnex(Annex annex) {
        this.annex = annex;
    }

    public List<Annex> getAnnexs() {
        return annexs;
    }

    public void setAnnexs(List<Annex> annexs) {
        this.annexs = annexs;
    }

    public TypeStamp getTypeStampObj() {
        return typeStampObj;
    }

    public void setTypeStampObj(TypeStamp typeStampObj) {
        this.typeStampObj = typeStampObj;
    }

    public Part getPart() {
        return part;
    }

    public void setPart(Part part) {
        this.part = part;
    }

    public List<CharterSDI> getCharterSDIs() {
        return charterSDIs;
    }

    public void setCharterSDIs(List<CharterSDI> charterSDIs) {
        this.charterSDIs = charterSDIs;
    }

    public Stamp getStamp() {
        return stamp;
    }

    public void setStamp(Stamp stamp) {
        this.stamp = stamp;
    }

    public List<Part> getParts() {
        return parts;
    }

    public void setParts(List<Part> parts) {
        this.parts = parts;
    }

    public CharterSDI getCharter() {
        return charter;
    }

    public void setCharter(CharterSDI charter) {
        this.charter = charter;
    }

    public CharterSDI getCharterShow() {
        return charterShow;
    }

    public void setCharterShow(CharterSDI charterShow) {
        this.charterShow = charterShow;
    }

    public People getPeople() {
        return people;
    }

    public List<Stamp> getStamps() {
        return stamps;
    }

    public void setStamps(List<Stamp> stamps) {
        this.stamps = stamps;
    }

    public void setPeople(People people) {
        this.people = people;
    }

    public void typeDocumentPeople() {
        System.err.println(people.getTipoDocumento());
    }

    public List<SelectItem> enumPropertySystem() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (PropertySystem tipo : PropertySystem.values()) {
            items.add(new SelectItem(tipo, tipo.getName()));
        }
        return items;
    }

    public List<SelectItem> typeDocumentList() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (TypeDocument tipo : TypeDocument.values()) {
            items.add(new SelectItem(tipo.getType(), tipo.getName()));
        }
        return items;
    }

    public List<Quality> autocompleteQuality(String str) {
        return qualityService.autoComplete(str);
    }

    public List<SelectItem> partQualitytList() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (Quality tipo : qualityService.findAll()) {
            items.add(new SelectItem(tipo, tipo.getDescription()));
        }
        return items;
    }

    public void addParts() {
        if (people.getName().isEmpty() || people.getName() == null) {
            Msg.messagemError("O nome da parte é obrigatório");
            return;
        }

        if (part.getPartQuality() != null) {
            part.setPartQuality(qualityService.find(part.getPartQuality().getId()));
        }
        part.setPeople(people);
        parts.add(part);
        people = new People();
        people.setTipoDocumento(TypeDocument.CPF);
        part = new Part();

    }

    public void addPartsEdit() {

        if (peopleEdit.getName().isEmpty() || peopleEdit.getName() == null) {
            Msg.messagemError("O nome da parte é obrigatório");
            return;
        }

        if (partEdit.getPartQuality() != null) {
            partEdit.setPartQuality(qualityService.find(partEdit.getPartQuality().getId()));
        }

        partEdit.setPeople(peopleEdit);
        charterEdit.getParts().add(partEdit);

        peopleEdit = new People();
        peopleEdit.setTipoDocumento(TypeDocument.CPF);
        partEdit = new Part();

    }

    public void ajaxVerifyPeopleExistEdit() {
        String doc = "";
        if (peopleEdit.getTipoDocumento() == TypeDocument.CNPJ) {
            doc = peopleEdit.getCnpj();
        } else if (peopleEdit.getTipoDocumento() == TypeDocument.CPF) {
            doc = peopleEdit.getCpf();
        } else if (peopleEdit.getTipoDocumento() == TypeDocument.OAB) {
            doc = peopleEdit.getOAB();
        }
        if (doc == null || doc.isEmpty()) {
            return;
        }
        People pe = peopleService.existPeople(peopleEdit.getTipoDocumento(), doc);
        if (pe != null) {
            peopleEdit = pe;
        }
    }

    public void removePart(int p) {
        charterEdit.getParts().remove(p);
    }

    public void removeStamp(int p) {
        charterEdit.getStamp().remove(p);
    }

     public void removeAnnexAux(Annex p) {
        annexToRemove = p;
    }
    
    public void removeAnnex() {
        if(annexToRemove!= null){
            charterEdit.getAnnex().remove(annexToRemove);
        }
    }
    
    public void addStamps() {
        stamp.setTypeStamp(typeStampService.find(typeStampObj.getId()));
        stamps.add(stamp);
        stamp = new Stamp();
    }

    public void addStampsEdit() {
        stampEdit.setTypeStamp(typeStampService.find(typeStampObjEdit.getId()));
        charterEdit.getStamp().add(stampEdit);
        stampEdit = new Stamp();
    }

    public void handle(FileUploadEvent event) throws IOException {
        System.err.println("Annexando" + event.getFile().getFileName());
        handleAux(event.getFile().getContents(), event.getFile().getFileName(),
                event.getFile().getContentType(), event.getFile().getInputstream());
    }

    private void handleAux(byte[] imageBytes, String nome, String tipo, InputStream is) throws IOException {

        byte[] bytes = null;

        annex = new Annex();
        if (tipo.equalsIgnoreCase("image/tiff")) {
            bytes = ConverterImg.convertTiffToJpg(is);
            annex.setType("jpeg");
            annex.setDescription(nome.replaceAll("tif|tiff", "jpeg"));
        } else {
            bytes = imageBytes;
            annex.setType(tipo);
            annex.setDescription(nome);
        }
        if (bytes != null) {
            annex.setFileByte(bytes);
            charterEdit.getAnnex().add(annex);
            System.err.println("Annexoo..." + annexs.size());
            annex = new Annex();
            Msg.messagemWarn("Anexado");
        }

    }

    public void create() {
        System.err.println(annexs);
        charter.setAnnex(annexs);
        charter.setStamp(stamps);
        People person;
        for (Part p : parts) {
            if (p.getPeople().getTipoDocumento() == TypeDocument.CPF) {
                person = peopleService.existPeople(TypeDocument.CPF, p.getPeople().getCpf());
            } else {
                person = peopleService.existPeople(TypeDocument.CNPJ, p.getPeople().getCnpj());
            }
            if (person != null) {
                p.setPeople(person);
            } else {
                if (p.getPeople().getId() == null) {
                    peopleService.save(p.getPeople());
                } else {
                    peopleService.update(p.getPeople());
                }
            }
        }

        charter.setParts(parts);
        System.err.println(charter);
        charterService.save(charter);
        charter = new CharterSDI();
        parts = new ArrayList<Part>();
        annexs = new ArrayList<Annex>();
        Msg.messagemInfo("Cadastrado com Sucesso !");
    }

    public void ajaxVerifyPeopleExist() {
        String doc = "";
        if (people.getTipoDocumento() == TypeDocument.CNPJ) {
            doc = people.getCnpj();
        } else if (people.getTipoDocumento() == TypeDocument.CPF) {
            doc = people.getCpf();
        } else if (people.getTipoDocumento() == TypeDocument.OAB) {
            doc = people.getOAB();
        }
        People pe = peopleService.existPeople(people.getTipoDocumento(), doc);
        if (pe != null) {
            people = pe;
        }
    }

    public void search() {
        part.setPeople(people);
        System.err.println("Book: " + charter.getBook());
        charterSDIs = charterService.searchCharter(charter, part, stamp);
    }

    public void edit() {
        charterService.update(charterEdit);
        Msg.messagemInfo("Atualizado com Sucesso !");
        charterEdit.setAnnex(annexService.getAnnexByCharter(charterEdit));
    }
}
